package com.zlm.custom.proxy;

import java.lang.reflect.Field;

/**
 * @author zlm
 * @date 2025/4/22
 */
public class Main {
    public static void main(String[] args) throws Exception {
        MyInterface myProxy = MyInterfaceFactory.createProxyInstance(new PrintFunctionName());
        myProxy.func1();
        myProxy.func2();
        myProxy.func3();


        MyInterface logInterface = MyInterfaceFactory.createProxyInstance(new LogHandler(myProxy));
        logInterface.func1();
        logInterface.func2();
        logInterface.func3();
    }

    static class PrintFunctionName implements MyHandler{
        @Override
        public String functionBody(String methodName) {
            String stringBuilder = "System.out.println(1);"+
                    "System.out.println(\"调用了" + methodName + "方法\");";
            return stringBuilder;
        }
    }

    static class LogHandler implements MyHandler{

        private MyInterface myInterface;

        public LogHandler(MyInterface myInterface) {
            this.myInterface = myInterface;
        }



        @Override
        public void setProxy(MyInterface proxy){
            try {
                Class<? extends MyInterface> aClass = proxy.getClass();
                Field field = aClass.getDeclaredField("myInterface");
                field.setAccessible(true);
                field.set(proxy,myInterface);
            } catch (Exception e){
                throw new RuntimeException(e);
            }
        }

        @Override
        public String functionBody(String methodName) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(" System.out.println(\"before\");\n")
                    .append("         myInterface.func1(); \n")
                    .append("         System.out.println(\"after\");\n");
            return stringBuilder.toString();
        }
    }
}
